using Basis;
using NL.AdreesableAsset;
using NL.Combat;
using System.Collections.Generic;
using UnityEngine;

namespace NL.Advanced
{
    public delegate IFBuff IFBuffAction<T>(T t);

    public class IFBuff : NLInfo
    {
        public int id;


        [Header("图标")]
        [SerializeField] private Sprite _Icon;

        [Header("启动特效;跳动特效")]
        [SerializeField] private GameObject _EFF_Start;
        [SerializeField] private GameObject _EFF_Beat;
        GameObject _Eff_Start;

        protected override void OnLoaded()
        {
            base.OnLoaded();

        }

        public GameObject EFF_Start
        {
            get
            {
                if (_EFF_Start == null)
                {
                    AA.LOAD<GameObject>(this["eff_start"], (url, w) =>
                    {
                        _Eff_Start = w;
                    });
                }

                return _Eff_Start;
            }
        }

        public GameObject EFF_Beat
        {
            get
            {
                if (_EFF_Beat == null)
                {
                    AA.LOAD<GameObject>(this["eff_beat"], (url, w) =>
                    {
                        _EFF_Beat = w;
                    });
                }

                return _EFF_Beat;
            }
        }

        public Sprite Icon
        {
            get
            {
                if (_Icon == null)
                {
                    AA.LOAD<Sprite>(this["icon"], (url, w) =>
                    {
                        _Icon = w;
                    });
                }

                return _Icon;
            }
        }
    }
    public class _BuffBase : MonoBehaviour, IObjStater, IPauseable, IAttackerOwner
    {
        [Header("指定ID.获取数据表内容")]
        public int ID;
        public int Group;
        public int OverlayMax;
        public BuffReplaceType Replace;

        [Header("生命时长,0:无限制")]
        public float Life = 5f;

        [Header("生效 得跳动间隔. 0代表不跳动")]
        public float Duration = 0;

        [Header("延迟启动")]
        public float Delay = 0;

        public string Property;
        public string PropertyBeat;

        //给对于对象得状态集合..
        public ObjState StateMask;
        ObjState IObjStater.State => StateMask;

        public string URL_EFF_Start, URL_EFF_Beat;

        public GameObject Mod_EFF_Start, Mod_EFF_Beat;

        public BB BBOwner { get; set; }
        ICombatOwner IAttackerOwner.CombatOwner => CombatFrom;
        void IAttackerOwner.SetCombat(ICombatOwner _owner, BB _bb) => SetCombat(_owner, _bb);

        public _BuffBase SetCombat(ICombatOwner _owner, BB _bb)
        {
            CombatFrom = _owner;
            BBOwner = _bb;
            return this;
        }
        public void Relife()
        {
            Lifing = 0;
        }
        public void Pause()
        {
            enabled = false;
        }

        public void Resume()
        {
            enabled = true;
        }

        static uint _INSTANCEIDCLOCK = 8000;




        [Header("----RUNTIME-----")]
        public uint UUD;

        protected int Level;

        public float Lifing = 0;

        protected ICombatOwner CombatFrom, CombatOwner;

        protected Attacker[] _Attackers;

        protected GameObject _Eff_Start, _Eff_Beat;
        protected int MaxLayer = 1;
        protected BuffReplaceType ReplaceType;





        // ILevelStateOwner _LevelOwner;

        private void Awake()
        {
            UUD = _INSTANCEIDCLOCK++; Living = false;
        }
        IPropertyOwner _PropertyOwner;
        //int _BuffID;
        protected virtual void Start()
        {
            gameObject.name = $"BUFF-{ID}[{UUD}]";

            CombatOwner = GetComponentInParent<ICombatOwner>();

            // 向属主注册自己..
            CombatOwner.ListenBuff(this);
            //_LevelOwner = GetComponentInParent<ILevelStateOwner>();

            if (CombatOwner == null)
            {
                Dead(); return;
            }



            _Attackers = GetComponents<Attacker>();




            Invoke("_Live", Delay);

        }
        bool Living = false;

        protected virtual void _Live()
        {
            LOG.Add($"[_BuffBase._Live({name})] :");
            Living = true;
            Lifing = 0;
            LoopPasssed = 0;

            _PropertyOwner = GetComponentInParent<IPropertyOwner>();
            //添加跳动特效
            if (!string.IsNullOrEmpty(URL_EFF_Start))
            {

                AA.LOAD<GameObject>(URL_EFF_Start, (url, w) =>
                {
                    Mod_EFF_Start = w;
                    _Eff_Start = EFF.CreateEFF(Mod_EFF_Start, CombatOwner.gameObject);

                });

            }
            else
            {
                _Eff_Start = EFF.CreateEFF(Mod_EFF_Start, CombatOwner.gameObject);
            }
            //处理状态.
            if (StateMask != ObjState.None && CombatOwner != null)
            {
                CombatOwner.StateAdd(this);
            }

            //处理属性
            _DoProperty();

            //处理供给部...
            _DoAttacker();
        }


        List<int> _PropertyIDAdded = new List<int>();
        protected virtual void DoBeat(bool forstart = false)
        {
            if (CombatOwner == null) return;
            //添加跳动特效
            if (!string.IsNullOrEmpty(URL_EFF_Beat))
            {

                AA.LOAD<GameObject>(URL_EFF_Beat, (url, w) =>
                {
                    Mod_EFF_Beat = w;
                    _Eff_Beat = EFF.CreateEFF(Mod_EFF_Beat, CombatOwner.gameObject);

                });

            }
            else
            {
                _Eff_Beat = EFF.CreateEFF(Mod_EFF_Beat, CombatOwner.gameObject);
            }

            _DoProperty(true);

            _DoAttacker();


            LOG.Add($"[_BuffBase._DoBeat({name})] :");
        }


        //处理属性
        void _DoProperty(bool forbeat = false)
        {
            var str = forbeat ? PropertyBeat : Property;

            if (!string.IsNullOrEmpty(str))
            {
                int? id = _PropertyOwner?.GetProperty()?.Add(str);

                if (id.HasValue)
                {
                    _PropertyIDAdded.Add(id.Value);
                }
            }
        }
        // 处理Attack
        void _DoAttacker()
        {
            if (CombatOwner != null && _Attackers != null)
            {
                foreach (var att in _Attackers)
                {
                    att?.SetBBOwner(BBOwner).Attack(CombatOwner);
                }
            }
        }


        protected virtual void OnDisable()
        {
            DoDead();
        }

        protected virtual void DoDisable()
        { 
            DoDead();
        }

        private void OnDestroy()
        {
            DoDead();
        }

        protected virtual void Clear()
        {

        }
        protected virtual void DoDead()
        {
            Destroy(gameObject);

            if (_Eff_Start != null)
            {
                _Eff_Start.SetActive(false);
            }
            
            if (_Eff_Beat != null)
            {
                _Eff_Beat.SetActive(false);
            }

            if (CombatOwner == null || !CombatOwner.Living) return;

            //如果还没激活..就不做处理..
            if (!Living) return;

            // 向属主 移除自己..
            CombatOwner.UnlistenBuff(this);
            //清理状态集合..
            CombatOwner.StateRemove(this);

            //移除添加得属性buff
            if (_PropertyOwner != null)
            {
                foreach (var id in _PropertyIDAdded)
                {
                    _PropertyOwner.GetProperty()?.Remove(id);
                }
                _PropertyIDAdded.Clear();
            }


        }


        public void Dead()
        {
            //Dead得时候 直接呼叫销毁....在OnDestroy得时候 统一处理逻辑..
            Destroy(gameObject);

        }



        float LoopPasssed = 0;
        public float RemainTime => Life - Lifing;



        protected void FixedUpdate()
        {
            //if (_LevelOwner != null && _LevelOwner.State != LevelState.Runing)
            //    return; 

            if (!Living) return;


            Lifing += Time.fixedDeltaTime;

            LoopPasssed += Time.fixedDeltaTime;

            if (Duration > 0 && LoopPasssed > Duration)
            {
                DoBeat();
                LoopPasssed -= Duration;
            }

            if (Life > 0 && Lifing > Life)
                Dead();
        }



        public _BuffBase AddLife(float _life)
        {
            Life += _life; return this;
        }
        public _BuffBase SetLife(float _life)
        {
            Life = _life;

            return this;
        }
        public _BuffBase SetProperty(string _property)
        {
            Property = _property;
            return this;
        }
        public _BuffBase SetObjState(ObjState state)
        {

            StateMask = state;

            return this;
        }
        public _BuffBase Set(float _life, NLIni _info, float _inteval = 0)
        {

            Life = _life;
            Duration = _inteval;

            return this;
        }

        public _BuffBase SetID(int id)
        {
            ID = id; return this;
        }

        public _BuffBase Set(ICombatOwner _owner)
        {
            CombatFrom = _owner; return this;
        }

    }
}

